package com.mfx.ziptest;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.io.ZipInputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private String TAG = "MainActivity";

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragmissions(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File zipdir = new File(getFilesDir(), "zipdir");
                zipdir.mkdir();
                copyAssets(zipdir.getPath()+"/old.zip");
                uncompressZip4j(zipdir.getPath()+"/old.zip",zipdir.getPath(),"");
            }
        }).start();

    }
    public  void copyAssets( String newPath) {
        try {
            InputStream is = MainActivity.this.getResources().getAssets().open("old.zip");

                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                    // buffer字节
                    fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                }
                fos.flush();// 刷新缓冲区
                is.close();
                fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * zip4j解压
     *
     * @param zipFilePath 待解压的zip文件（目录）路径
     * @param filePath    解压到的保存路径
     * @param password    密码
     * @return 状态返回值
     */
    public int uncompressZip4j(String zipFilePath, String filePath, String password) {
        File zipFile_ = new File(zipFilePath);
        File sourceFile = new File(filePath);
        try {

            ZipFile zipFile = new ZipFile(zipFile_);
            zipFile.setFileNameCharset("GBK"); //设置编码格式（支持中文）
            if (!zipFile.isValidZipFile()) {   //检查输入的zip文件是否是有效的zip文件
                throw new ZipException("压缩文件不合法,可能被损坏.");
            }
            if (sourceFile.isDirectory() && !sourceFile.exists()) {
                sourceFile.mkdir();
            }
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password.toCharArray());
            }
            zipFile.extractAll(filePath); //解压
            Log.i(TAG, "uncompressZip4j: 解压成功");
        } catch (ZipException e) {
            e.printStackTrace();
        }

        return 0;
    }
    private void verifyStoragmissions(Activity activity) {
        int permission1 = ActivityCompat.checkSelfPermission(activity,"android.permission.READ_EXTERNAL_STORAGE");
        int permission2 = ActivityCompat.checkSelfPermission(activity,"android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission1 != PackageManager.PERMISSION_GRANTED || permission2 != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        int n = grantResults.length;
        if (n < 1)
            return ;
        for (int i = 0; i < n; i++){
            if (PackageManager.PERMISSION_GRANTED != grantResults[i]){ //用户未授予权限定义中对应的权限
                //未授权，不能执行需要权限的操作。
            }else{
                //已授权可以执行相应操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        copyAssets(getFilesDir().getAbsolutePath()+"/imag/");
                    }
                }).start();
            }
        }
    }
}